package com.szqhyxj.youxiangju.biz.merchantHome.shop.pay;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.szqhyxj.youxiangju.biz.creditCardEvaluation.buycreditcardEvaluationSuccess.BuycreditcardEvaluationSuccessActicvity;
import com.szqhyxj.youxiangju.biz.equipmentActivation.activationSuccess.BuySlotSuccessActivity;
import com.szqhyxj.youxiangju.biz.equipmentActivation.headIdCard.HeadIdCardActivity;
import com.szqhyxj.youxiangju.biz.push.AddDeviceEvent;

import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 重要说明:
 * <p>
 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
 */
public class AliPayActivity extends FragmentActivity {
    public static final int CODE_2001 = 2001;
    public static final int CODE_2002 = 2002;
    public static final int PAY_START = 10086;
    public static final int PURCHASE = 1;
    public static final int BUYSLOT = 2;
    public static final int BUYCREDITCARD = 3;
    public static final int DISPOSE_SUCESS = 4;//支付成功跳转到激活页面
    public static final String ALIPAYINFO = "aliPayInfo";

    private String orderId;
    private String payAmount;
    private int type;


    public static void start(Activity activity, String aliPayInfo, int type) {
        Intent intent = new Intent();
        intent.setClass(activity, AliPayActivity.class);
        intent.putExtra(ALIPAYINFO, aliPayInfo);
        intent.putExtra("type", type);
        activity.startActivityForResult(intent, PAY_START);
    }
    public static OnCallBackListener onCallBackListener;
    public static void start(Activity activity, String aliPayInfo,OnCallBackListener listener) {
        Intent intent = new Intent();
        intent.setClass(activity, AliPayActivity.class);
        intent.putExtra(ALIPAYINFO, aliPayInfo);
        onCallBackListener=listener;
        activity.startActivityForResult(intent, PAY_START);
    }

    public  interface OnCallBackListener{
        void onSucess();
        void onError(String code);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String aliPayInfo = getIntent().getStringExtra("aliPayInfo");
        sendAlipayRequest(aliPayInfo);
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        Bundle bundle = new Bundle();
                        bundle.putString("result", resultInfo);
                        Intent intent = new Intent();
                        intent.putExtras(bundle);
                        setResult(CODE_2001, intent);
                        int type = getIntent().getIntExtra("type", 0);
                        if (type == PURCHASE) {

                        }
                        if (type == BUYSLOT) {
                            BuySlotSuccessActivity.start(AliPayActivity.this);
                        }
                        if(type==DISPOSE_SUCESS){
                            EventBus.getDefault().post(new PayState(true));
                        }
                        if (type == BUYCREDITCARD){
                            BuycreditcardEvaluationSuccessActicvity.start(AliPayActivity.this);
                        }

                        finish();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(AliPayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        setResult(CODE_2002);
                        if(type==DISPOSE_SUCESS){
                            EventBus.getDefault().post(new PayState(false));
                        }
                        finish();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    public void sendAlipayRequest(String info) {
        // 订单信息
        final String orderInfo = info;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AliPayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }


}
